package ru.pb.auth.network.engine.auth;

import org.apache.log4j.Logger;

import ru.pb.auth.network.clients.AuthClient;
import ru.pb.auth.network.engine.auth.packets.FromAuthClientToAuthServerPacket;
import ru.pb.auth.network.engine.auth.packets.receivable.PROTOCOL_BASE_GET_MYFRIENDS_REQ;
import ru.pb.auth.network.engine.auth.packets.receivable.PROTOCOL_BASE_GET_MYINFO_REQ;
import ru.pb.auth.network.engine.auth.packets.receivable.PROTOCOL_BASE_LOGIN_REQ;
import ru.pb.auth.network.engine.auth.packets.receivable.PROTOCOL_BASE_USER_LEAVE_REQ;
import ru.pb.auth.network.engine.auth.packets.receivable.opcode_2660;
import ru.pb.auth.network.engine.auth.packets.receivable.opcode_2667;
import ru.pb.global.network.engine.buffer.NioBuffer;
import ru.pb.global.network.engine.core.emuns.ConnectionState;
import ru.pb.global.network.engine.core.interfaces.IPacketHandler;
import ru.pb.global.network.utils.NetworkUtil;

/**
 * @author: Felixx
 *          Слушает пакеты игроков.
 */
public class AuthClientPacketListenerHandler implements IPacketHandler<AuthClient>
{
	private static Logger _log = Logger.getLogger(AuthClientPacketListenerHandler.class);
	private boolean _aviableConnections = true;

	@Override
	public FromAuthClientToAuthServerPacket handle(NioBuffer buf, AuthClient client)
	{
		FromAuthClientToAuthServerPacket packet = null;
		ConnectionState state = client.getState();
		int opcode = buf.getUnsignedShort();
		_log.info("Packet id: " + opcode + "; size: " + buf.limit() + "; pos:" + buf.position());
		if(_aviableConnections)
		{
			switch(state)
			{
				case CONNECTED:
				{
					switch(opcode)
					{
						case 0:
						{
							_aviableConnections = false;
							break;
						}
						case 2561:
						{
							packet = new PROTOCOL_BASE_LOGIN_REQ();
							break;
						}
						case 2565:
						{
							packet = new PROTOCOL_BASE_GET_MYINFO_REQ();
							break;
						}
						case 2567:
						{
							packet = new PROTOCOL_BASE_GET_MYFRIENDS_REQ();
							break;
						}
						case 2667:
						{
							packet = new opcode_2667(); // Настройки юзера помойму.
							break;
						}
						case 528: // Автритизация в Hack Shield
						{
							// packet = new opcode_528();
							break;
						}
						case 2660:
						{
							packet = new opcode_2660();
							break;
						}
						case 2577:
						{
							packet = new PROTOCOL_BASE_USER_LEAVE_REQ();
							break;
						}
						default:
						{
							debugOpcode(opcode, state, client, buf);
						}
					}
					break;
				}
			}
			return packet;
		}
		return null;
	}

	private void debugOpcode(int opcode, ConnectionState state, AuthClient client, NioBuffer buf)
	{
		_log.info("Unknown Opcode: " + opcode + " for state: " + state.name() + " from IP: " + client.getIPString());
		_log.info(NetworkUtil.printData(buf));
	}
}